package com.gongpingjialoan.activity.index;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.api.Piont;
import com.gongpingjialoan.bean.Monitor;
import com.gongpingjialoan.bean.UpdateBean;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.ApkUpdateUtils;
import com.gongpingjialoan.utility.StepMonitor;
import com.google.gson.Gson;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;

import java.io.File;
import java.util.List;

public class IndexActivity extends FragmentActivity {
    private FragmentManager fm;
    private Fragment currentFragment;

    private LinearLayout tabV;

    static boolean isExit = false;
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            isExit = false;
        }
    };

    Handler mHandler = new Handler();;

    Dialog progressdialog;
    private Toast mToast;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index);
        initView();
    }

    private void initView() {
        fm = getSupportFragmentManager();
        tabV = (LinearLayout) findViewById(R.id.tab);
        initTab();
        setTab(0);
        getNewVersion();
    }

    private void initTab() {
        for (int i = 0; i < tabV.getChildCount(); i++) {
            final int index = i;
            LinearLayout childV = (LinearLayout) tabV.getChildAt(i);
            childV.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    setTab(index);
                }
            });
        }
    }

    public void setTab(final int index) {
        for (int i = 0; i < tabV.getChildCount(); i++) {
            LinearLayout childV = (LinearLayout) tabV.getChildAt(i);
            RelativeLayout imgV = (RelativeLayout) childV.getChildAt(0);
            final ImageView imgI = (ImageView) imgV.getChildAt(0);
            final TextView textT = (TextView) childV.getChildAt(1);
            if (i == index) {
                textT.setTextColor(getResources().getColor(
                        R.color.text_black));
                switch (i) {
                    case 0: // 首页
                        switchContent(IndexFragment.getInstance());
                        imgI.setImageResource(R.drawable.sellcar_icon_select);
                        break;

                    case 1: // 选车
                        switchContent(FindCarFragment.getInstance());
                        imgI.setImageResource(R.drawable.sellcar_icon_select);
                        break;

                    case 2: // 车分期
                        switchContent(LoanFragment.getInstance());
                        imgI.setImageResource(R.drawable.sellcar_icon_select);

                        break;

                    case 4: // 我的
                        switchContent(MyFragment.getInstance());
                        imgI.setImageResource(R.drawable.sellcar_icon_select);
                        break;

                    default:
                        break;
                }
            } else {
                textT.setTextColor(getResources()
                        .getColor(R.color.text_grey_dark));
                switch (i) {
                    case 0:
                        imgI.setImageResource(R.drawable.sellcar_icon_normal);
                        break;

                    case 1:
                        imgI.setImageResource(R.drawable.sellcar_icon_normal);
                        break;

                    case 2:
                        imgI.setImageResource(R.drawable.sellcar_icon_normal);
                        break;

                    case 3:
                        imgI.setImageResource(R.drawable.sellcar_icon_normal);
                        break;
                    default:
                        break;
                }
            }
        }
    }

    public void switchContent(Fragment fragment) {
        try {
            FragmentTransaction t = fm.beginTransaction();
            if (currentFragment != null) {
                t.hide(currentFragment);
            }
            if (!fragment.isAdded()) {
                t.add(R.id.main_content, fragment);
            }
            t.show(fragment);
            t.commitAllowingStateLoss();
            currentFragment = fragment;
        } catch (Exception e) {
        }
    }

    private void getNewVersion() {
        NetDataJson updateNetDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
            }

            @Override
            public void onDataJsonUpdate(String json) {
                Gson gson = new Gson();
                UpdateBean updateBean = gson.fromJson(json, UpdateBean.class);
                if ("success".equals(updateBean.getStatus()) && updateBean.getData() != null && !TextUtils.isEmpty(updateBean.getData().getDownload_url())) {
                    upDate(updateBean);
                }
            }
        }, 1);
        updateNetDataJson.setUrl(API.update);
        updateNetDataJson.request("get");
    }

    private void upDate(final UpdateBean updateBean) {
        AlertDialog.Builder ab = new AlertDialog.Builder(this);
        ab.setTitle("发现新版本" + updateBean.getData().getVersion());
        ab.setMessage(updateBean.getData().getDescription());
        final boolean isForce = updateBean.getData().isForce_update();
        if (!isForce) {
            ab.setNegativeButton("忽略", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
        } else {
            ab.setNegativeButton("退出应用", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                    System.exit(0);
                }
            });
        }
        ab.setPositiveButton("更新", null);
        final AlertDialog alertDialog = ab.create();
        if (isForce) {
            alertDialog.setCancelable(false);
        }
        alertDialog.show();
        alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!canDownloadState()) {
                    Toast.makeText(IndexActivity.this, "请您启用下载服务", Toast.LENGTH_SHORT).show();
                    showDownloadSetting();
                    return;
                }
                ApkUpdateUtils.download(IndexActivity.this, updateBean.getData().getDownload_url(), getResources().getString(R.string.app_name), isForce);
                if (!isForce) {
                    alertDialog.dismiss();
                }
            }
        });
    }
    private void showDownloadSetting() {
        String packageName = "com.android.providers.downloads";
        Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + packageName));
        if (intentAvailable(intent)) {
            startActivity(intent);
        }
    }
    private boolean intentAvailable(Intent intent) {
        PackageManager packageManager = getPackageManager();
        List list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }

    private boolean canDownloadState() {
        try {
            int state = this.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");

            if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!isExit) {
                isExit = true;
                mToast = Toast.makeText(this, "再按一次退出程序",
                        Toast.LENGTH_SHORT);
                mToast.show();
                mHandler.postDelayed(runnable, 2000);
            } else {
                mToast.cancel();
                System.exit(0);
            }

            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacks(runnable);
    }


}
